package club.kingyin.kyblogprosearch.client;

import co.elastic.clients.elasticsearch.ElasticsearchClient;

import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.springframework.beans.factory.annotation.Value;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Configuration;


@Configuration
public class ElasticClient {

    private static final String username = "elastic";
    private static final String password = "578145931";
    private static final Integer connectionRequestTimeout = 0;
    private static final Integer socketTimeout = 30000;
    private static final Integer connectTimeout = 5000;


    public static ElasticsearchClient client() {
        RestClient restClient = RestClient.builder(
                new HttpHost("test2.kingyin.club", 9200)
        )
                .setHttpClientConfigCallback(httpAsyncClientBuilder->{
                    //账密设置
                    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                    //es账号密码（一般使用,用户elastic）
                    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
                    httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    return httpAsyncClientBuilder;
                })
                .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder
                        .setConnectionRequestTimeout(connectionRequestTimeout)
                        .setSocketTimeout(socketTimeout)
                        .setConnectTimeout(connectTimeout))
                .build();

        RestClientTransport restClientTransport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        return new ElasticsearchClient(restClientTransport);

    }

}
